package com.ndp.fb.rdb.mongo.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.*;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.mongo.api.ActivityLogMongoService;
import com.ndp.fb.mongo.model.ActivityLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ActivityLogMongoServiceImpl implements ActivityLogMongoService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DB mongoDBClient;

    @Override
    public void upsertActivityLogs(List<ActivityLog> activityLogs) {
        if (CollectionUtils.isNotEmpty(activityLogs)) {
            Long start = System.currentTimeMillis();
            int size = activityLogs.size();
            DBCollection dbCollection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACTIVITY_LOG);
            List<DBObject> tmpList = (List<DBObject>) com.mongodb.util.JSON.parse(JSONObject.toJSONString(activityLogs));
            DBObject updateData;
            DBObject o = new BasicDBObject();
            for (DBObject dbObject : tmpList) {
                updateData = new BasicDBObject();
                dbObject.put("mongodbId", dbObject.get("object_id") + "_" + dbObject.get("event_utc_time") + "_" + dbObject.get("event_type"));
                updateData.put("$set", dbObject);
                Date dateUpdateTime = new Date();
                dbObject.put("dataUpdateTime", dateUpdateTime);
                o.put("mongodbId", dbObject.get("object_id") + "_" + dbObject.get("event_utc_time") + "_" + dbObject.get("event_type"));
                dbCollection.update(o, updateData, true, false);
            }
            logger.debug("本次总共更新ActivityLog数据{}条,花费时间为{}", size, System.currentTimeMillis() - start);
        }
    }

    @Override
    public List<ActivityLog> findActivityLogs(Long object_id, String type) {
        DBCollection dbCollection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACTIVITY_LOG);
        DBObject o = new BasicDBObject();
        o.put("object_id", object_id);
        o.put("event_type", type);
        DBCursor dbCursor = dbCollection.find(o);
        if (dbCursor == null) {
            return null;
        }
        List<ActivityLog> activityLogs = new ArrayList<>();
        while (dbCursor.hasNext()) {
            activityLogs.add(JSONObject.parseObject(JSONObject.toJSONString(dbCursor.next()), ActivityLog.class));
        }
        return activityLogs;
    }
}
